package com.boot2523.service;

import com.boot2523.bean.User;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserRedisS2 {
    @Resource
    public RedisTemplate<String,Object> redisTemplate;
    //模拟数据库
    public Map<String, User> data= Collections.synchronizedMap(new HashMap<>());
    public UserRedisS2(){
        data.put("user1",new User(1,"tom","10"));
        data.put("user2",new User(2,"mary","12"));
        data.put("user3",new User(3,"jack","14"));
    }
    public User get(String key){
        //从redis获取数据 如果redis没有，则出现内存击穿,如果大量用户并发访问,出现雪崩（数据库宕机）
        User myuser=(User)redisTemplate.opsForValue().get(key);
        if (myuser==null){
            //添加同步锁
            synchronized (key.intern()){
                //再查询
                myuser=(User)redisTemplate.opsForValue().get(key);
                if(myuser==null) {
                    //查询数据库，将数据存入缓存
                    myuser=data.get(key);
                    if (myuser != null) {
                        //设置缓存并设定有效时间
                        redisTemplate.opsForValue().set(key, myuser, 5, TimeUnit.HOURS);
                    }
                }
            }
        }
        return myuser;
    }
}
